"use strict";
this.ModuleLoader = function () {};

this.ModuleLoader.prototype = (function () {
    var init, thread, onConfigurationLoaded, configuration, container,
            directoryAutodetection, document, loadModules;

    document = this.document;

    init = function () {
        container = this.container;
    };

    thread = function () {};

    onConfigurationLoaded = function (webLayout, config) {
        var modules, dir;
        if (config[this.NAME] === undefined) {
            return;
        }
        configuration = config;
        modules = config[this.NAME].modules;
        dir = config[this.NAME].dir === undefined ? directoryAutodetection() :
                config[this.NAME].dir;
        loadModules(modules, dir, webLayout);
    };

    loadModules = function (modules, dir, webLayout) {
        var i;
        dir = dir === '' ? '' : dir + '/';
        for (i = modules.length - 1; i >= 0; i -= 1) {
            webLayout.ajaxLib.get(dir + modules[i].toLowerCase() + '.js', '',
                    function () {
                var module = modules[i];
                return function (response, status, xhr) {
                    try {
                        container.evaluator(response);
                        module = new container[module]();
                        webLayout.addModule(module);
                        if (module.onConfigurationLoaded instanceof Function) {
                            module.onConfigurationLoaded(webLayout,
                                    configuration);
                        }
                    } catch (e) {}
                };
            }());
        }
    };

    directoryAutodetection = function () {
        var scripts, i;
        scripts = document.getElementsByTagName('script');
        for (i = scripts.length - 1; i >= 0; i -= 1) {
            if (scripts[i].src.toLowerCase().indexOf('initloader.js') > -1) {
                return scripts[i].src.replace(/\/initloader\.js$/i, '');
            }
        }
        return '';
    };

    return {
        NAME: 'ModuleLoader',
        init: init,
        thread: thread,
        onConfigurationLoaded: onConfigurationLoaded
    };
}());

this.ModuleLoader.prototype.container = this;